package com.gjintel.framework.user.controller;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.activiti.engine.IdentityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gjintel.framework.cache.InitCacheData;
import com.gjintel.framework.cache.InitCacheData.CacheType;
import com.gjintel.framework.constant.ActivitiMap;
import com.gjintel.framework.constant.Constant;
import com.gjintel.framework.constant.Constant.RightType;
import com.gjintel.framework.dept.model.Dept;
import com.gjintel.framework.dict.model.Dictionary;
//import com.gjintel.framework.goodstype.model.GoodsType;
import com.gjintel.framework.log.model.LogInfo;
import com.gjintel.framework.log.util.LogUtil;
import com.gjintel.framework.log.util.LogUtil.LogType;
import com.gjintel.framework.role.model.Role;
import com.gjintel.framework.role.service.IRoleService;
import com.gjintel.framework.user.model.User;
import com.gjintel.framework.user.service.IUserService;
import com.gjintel.framework.util.CommUtil;
import com.gjintel.framework.util.DictUtil;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.util.MD5Lock;
import com.gjintel.sdk.util.StringUtil;

@RequestMapping("/framework/user")
@Controller
public class UserController {
	@Autowired
	private IUserService userService;
	@Autowired
	private IRoleService roleService;
	 @Autowired
	private  IdentityService identityService; 


	/**
	 * @description 根据ID对角色信息进行添加、修改操作
	 * @author fengya
	 * @date 2015-7-23 下午04:40:09
	 * @param id
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/input")
	public ModelAndView input(String id) {
		ModelAndView mv = new ModelAndView("/framework/user/user-input");
		if (!StringUtil.isEmpty(id)) {
			User user = userService.get(User.class, id);
			this.compUser(user);
			mv.addObject("user", user);
		}
		return mv;
	}

	/**
	 * @description 得到用户树
	 * @author fengya
	 * @date 2015-8-4 下午04:51:18
	 * @param nodeName
	 * @param id
	 * @param selectIds
	 * @return
	 * @return JSONObject
	 * @throws UnsupportedEncodingException
	 */
	// @RequestMapping("/getUserTree")
	// @SuppressWarnings("unchecked")
	// @ResponseBody
	// public JSONObject getUserTree(String nodeName, String id, String
	// selectIds) throws UnsupportedEncodingException {
	// // 树中节点所在的集合
	// List<TreeDto> treeList = new ArrayList<TreeDto>();
	// if (!StringUtil.isEmpty(nodeName)) {
	// nodeName = URLDecoder.decode(nodeName, "UTF-8");
	// }
	// Map jsonData = new HashMap();
	// // 查询到的节点ID的集合
	// List<String> selIds = this.deptService.getUserTree(treeList, id,
	// nodeName, selectIds);
	// jsonData.put("selIds", JSONArray.fromObject(selIds));
	// jsonData.put("tree", JSONArray.fromObject(treeList));
	// return JSONObject.fromObject(jsonData);
	// }

	/**
	 * @description 完善用户的机构和职务信息
	 * @author fengya
	 * @date 2015-7-31 下午01:26:44
	 * @param user
	 * @return void
	 */
	private void compUser(User user) {
		if (!StringUtil.isEmpty(user.getDeptId())) {
			Object obj = InitCacheData.getInstance().getCacheData(InitCacheData.CacheType.DEPT).get(user.getDeptId());
			if (obj != null) {
				Dept dept = (Dept) obj;
				user.setDeptName(dept.getName());
			}
		}
	}

	@RequestMapping("/getUsers")
	@SuppressWarnings("unchecked")
	@ResponseBody
	public JSONObject getUsers(Page page, String userType, Sort sort) {
		this.userService.getUsers(page, userType, sort);
		if (!page.getResult().isEmpty()) {
			Iterator<User> userIt = page.getResult().iterator();
			User user = null;
			while (userIt.hasNext()) {
				user = userIt.next();
				this.compUser(user);
			}
		}
		return CommUtil.getPageJSONData(page, true);
	}

	@RequestMapping("/roleUsers")
	@SuppressWarnings("unchecked")
	@ResponseBody
	public JSONObject roleUsers(Page page, String roleId, Sort sort, boolean roleUser) {
		this.userService.roleUsers(page, roleId, sort, roleUser);
		if (!page.getResult().isEmpty()) {
			Iterator<User> userIt = page.getResult().iterator();
			User user = null;
			while (userIt.hasNext()) {
				user = userIt.next();
				this.compUser(user);
			}
		}
		return CommUtil.getPageJSONData(page, true);
	}

	/**
	 * @description 对用户绑定角色
	 * @author fengya
	 * @date 2015-7-31 下午01:29:43
	 * @param deleteIds
	 * @param roleId
	 * @return
	 * @return String
	 */
	@RequestMapping("/bindRole")
	@ResponseBody
	public String bindRole(HttpSession session, String deleteIds, String roleId) {
		User sUser = (User) session.getAttribute("loginUser");
		this.userService.saveOrUpdate(this.userService.bindRole(sUser, deleteIds, roleId));
		return Constant.BIND_SUCCESS;
	}

	@RequestMapping("/index")
	public ModelAndView index(HttpSession session) {
		ModelAndView mv = new ModelAndView("/framework/user/user");
		User sUser = (User) session.getAttribute("loginUser");
		String userRightData = this.userService.getUserRightData(sUser.getId());
		//if (userRightData.contains(RightType.SAME_LEVEL_USER.toString().toLowerCase()) || sUser.getId().equals("1")) {
			mv.addObject("isRight", true);
		//}
		return mv;
	}

	/**
	 * @方法名：list
	 * @功能说明：根据查询条件获得消息类型记录
	 * @author fengya
	 * @date 2014-5-30 下午04:39:36
	 * @return void
	 */
	@RequestMapping("/list")
	@SuppressWarnings("unchecked")
	@ResponseBody
	public JSONObject list(HttpSession session, Page page, User user, Sort sort,String roles) {
		User sUser = (User) session.getAttribute("loginUser");
		int loginUserType = 0;
		Dept loginDept = (Dept) InitCacheData.getInstance().getCacheData(CacheType.DEPT).get(sUser.getDeptId());
		if (sUser.getId().equals("1")) {
			loginUserType = 1;
		}
		this.userService.findAll(page, user, sort, loginUserType, loginDept.getpUnit(),roles);
		if (!page.getResult().isEmpty()) {
			Iterator<User> userIt = page.getResult().iterator();
			User temp = null;
			List<Role> userRoles;
			while (userIt.hasNext()) {
				temp = userIt.next();
				if (!StringUtil.isEmpty(temp.getSex())) {
					temp.setSexName(DictUtil.dict("sex", temp.getSex()).getName());
				}
				this.compUser(temp);
				userRoles = this.userService.getUserRole(temp.getId());
				if (!userRoles.isEmpty()) {
					for (int i = 0; i < userRoles.size(); i++) {
						if (i == 0) {
							temp.setRoleName(userRoles.get(i).getName());
						} else {
							temp.setRoleName(temp.getRoleName() + "," + userRoles.get(i).getName());
						}
					}
				}
				// 用户类型
//				if (!StringUtil.isEmpty(temp.getType())) {
//					temp.setTypeName(DictUtil.dict("user_type", temp.getType()).getName());
//				}
			}
		}
		return CommUtil.getPageJSONData(page, true);
	}

	// private String getLoginUserUnitIds(String loginUserDeptId){
	// List<String> deptIds = new ArrayList<String>();
	// this.setLoginUserUnitIds(loginUserDeptId, deptIds);
	// StringBuilder userDeptUnit = new StringBuilder();
	// for(int i=0;i<deptIds.size();i++){
	// if(i == 0){
	// userDeptUnit.append("\'").append(deptIds.get(i)).append("\'");
	// } else {
	// userDeptUnit.append(",").append("\'").append(deptIds.get(i)).append("\'");
	// }
	// }
	// return userDeptUnit.toString();
	// }

	private void setLoginUserUnitIds(String pDeptId, List<String> deptIds) {
		List<Object> loginDeptList = InitCacheData.getInstance().getCacheTreeData(CacheType.DEPT).get(pDeptId);
		if (loginDeptList != null) {
			Dept dept = null;
			for (Object obj : loginDeptList) {
				dept = (Dept) obj;
				deptIds.add(dept.getId());
				this.setLoginUserUnitIds(dept.getId(), deptIds);
			}
		}
	}

	/**
	 * @方法名：save
	 * @功能说明：保存记录数据
	 * @author fengya
	 * @date 2014-5-30 上午09:28:49
	 * @return void
	 */
	@RequestMapping("/save")
	@ResponseBody
	public String save(HttpSession session, User user) {
		User sUser = (User) session.getAttribute("loginUser");
		if (user != null) {
			boolean sign = false;
			if (StringUtil.isEmpty(user.getId())) {
				user.setId(null);
				user.setCreateTime(new Date());
				user.setCreaterName(sUser.getName());
				user.setCreaterId(sUser.getId());
				user.setPsw(MD5Lock.lock(user.getPsw()));
				sign = true;
			} else {
				User temp = (User) InitCacheData.getInstance().getCacheData(CacheType.USER).get(user.getId());
				if (user.getPsw() != null && !user.getPsw().equals(temp.getPsw())) {
					user.setPsw(MD5Lock.lock(user.getPsw()));
				}
			}
			user.setUpdateTime(new Date());
			user.setUpdaterName(sUser.getName());
			user.setUpdaterId(sUser.getId());
			this.userService.saveOrUpdate(user);
			// 开始同步act_id_user表
			saveActivitiRegisterUser(user);
			InitCacheData.getInstance().initUserData();
			if (sign) {
				LogUtil.addLog(new LogInfo("添加用户信息", user.getId(), user.getName(), String.valueOf(LogType.ADD.ordinal()), user.getClass().getSimpleName(), user.getId()));			
						
						// 添加act_id_membership 关联
					//	addMembershipToIdentify(user);

			} else {
				LogUtil.addLog(new LogInfo("更新用户信息", user.getId(), user.getName(), String.valueOf(LogType.UPDATE.ordinal()), user.getClass().getSimpleName(), user.getId()));
			}
			
			return Constant.SAVE_SUCCESS;
		}
		return Constant.SAVE_UN_SUCCESS;
	}

	/**
	 * 
	 * @description 修改密码
	 * @author hong
	 * @date 2015-8-31 上午10:07:56
	 * @param session
	 * @param oldPsw
	 * @param psw
	 * @param psw1
	 * @return
	 * @return String
	 */
	@RequestMapping("/savePassword")
	@ResponseBody
	public String savePassword(HttpSession session, String oldPsw, String psw, String psw1) {
		User user1 = new User();
		User sUser = (User) session.getAttribute("loginUser");
		String id = sUser.getId();
		if (!StringUtil.isEmpty(id)) {
			user1 = userService.get(User.class, id);// 根据id查找当前用户
		}
		if (!StringUtil.isEmpty(psw)) {
			user1.setUpdateTime(new Date());
			String oldPswInput = MD5Lock.lock(oldPsw);
			if (oldPswInput.equals(user1.getPsw()) && psw.equals(psw1) && psw.length() >= 6) {
				user1.setPsw(MD5Lock.lock(psw));
				this.userService.saveOrUpdate(user1);
				LogUtil.addLog(new LogInfo("修改密码", sUser.getId(), sUser.getName(), String.valueOf(LogType.UPDATE.ordinal()), user1.getClass().getSimpleName(), user1.getId()));

				return Constant.SAVE_SUCCESS;
			} else {
				return Constant.SAVE_UN_SUCCESS;
			}
		} else {
			return Constant.SAVE_UN_SUCCESS;
		}
	}

	/**
	 * @方法名：remove
	 * @功能说明：根据选择的记录进行删除数据
	 * @author fengya
	 * @date 2014-4-17 下午04:13:04
	 * @return void
	 */
	@RequestMapping("/remove")
	@ResponseBody
	public String remove(HttpSession session, String deleteIds) {
		User user = (User) session.getAttribute("loginUser");
		this.userService.removeData(deleteIds);
		LogUtil.addLog(new LogInfo("删除用户数据", user.getId(), user.getName(), String.valueOf(LogType.DELETE.ordinal()), User.class.getSimpleName(), deleteIds));
		return Constant.DEL_SUCCESS;
	}

	/**
	 * 
	 * @description 跳转到个人资料
	 * @author hong
	 * @date 2015-8-31 上午10:09:06
	 * @param req
	 * @param session
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/openPersonExeDialog")
	public ModelAndView openPersonExeDialog(HttpServletRequest req, HttpSession session) {
		// 从session中取user的id
		User user = (User) session.getAttribute("loginUser");
		String id = user.getId();
		ModelAndView mv = new ModelAndView("/framework/user/person-input");
		if (!StringUtil.isEmpty(id)) {
			user = userService.get(User.class, id);// 根据id查找当前用户
			this.compUser(user);
			mv.addObject("user", user);
		}
		return mv;
	}

	/**
	 * 
	 * @description 跳转到修改密码页面
	 * @author hong
	 * @date 2015-8-31 上午10:08:22
	 * @param req
	 * @param session
	 * @return
	 * @return ModelAndView
	 */
	@RequestMapping("/changePassword")
	public ModelAndView changePassword(HttpServletRequest req, HttpSession session) {
		// 从session中取user的id
		User user = (User) session.getAttribute("loginUser");
		String id = user.getId();
		ModelAndView mv = new ModelAndView("/framework/user/change-password");
		if (!StringUtil.isEmpty(id)) {
			user = userService.get(User.class, id);// 根据id查找当前用户
			this.compUser(user);
			mv.addObject("user", user);
		}
		return mv;
	}

	/**
	 * 用户管理-权限管理页面
	 * 
	 * @return ModelAndView
	 */
	@RequestMapping("/rightManagePage")
	public ModelAndView rightManagePage(HttpSession session, String userId, String userType) {
		ModelAndView mv = new ModelAndView("/framework/user/right-manage");
		List<Role> roleList = roleService.findRoleListExcludeAdmin(ActivitiMap.BIDDER_ID);
		mv.addObject("roleList", roleList);
		if (!StringUtil.isEmpty(userId)) {
			mv.addObject("userRoleData", userService.getUserRoleData(userId));
		}
		if (!StringUtil.isEmpty(userType) && userType.trim().equals("0")) {
			User sUser = (User) session.getAttribute("loginUser");
			List<Dictionary> rightList = null;
			String userRightData = null;
			if (sUser.getId().equals("1")) {
				// 说明当前操作用户是超级管理员
				rightList = DictUtil.dictChildren("set_right");
				userRightData = this.userService.getUserRightData(userId);
			} else {
				// 当前是分级管理员操作
				rightList = this.userService.getUserRights(sUser.getId());
				userRightData = this.userService.getUserRightData(userId);
			}
			mv.addObject("rightList", rightList);
			mv.addObject("userRightData", userRightData);
		}
		return mv;
	}

	/**
	 * @description 用户权限管理
	 * @date 2015-7-31 下午01:29:43
	 * @param deleteIds
	 * @param roleId
	 * @return
	 * @return String
	 */
	@RequestMapping("/saveRightData")
	@ResponseBody
	public String saveRightData(HttpSession session, String userId, String roleIds, String rightDictVal, String goodsTypeIds) {
		User sUser = (User) session.getAttribute("loginUser");
		this.userService.saveRightData(sUser, userId, roleIds, rightDictVal, goodsTypeIds);
		return Constant.BIND_SUCCESS;
	}
	
	 /**
	   * 添加一个用户到Activiti {@link org.activiti.engine.identity.User}
	   * @param user  用户对象, {@link User}
	   */
	  public  void saveActivitiRegisterUser(User user) {
	    String userId = user.getId().toString();
	    org.activiti.engine.identity.User activitiUser=identityService.createUserQuery().userId(userId).singleResult();
	    if(activitiUser==null){
	    	 activitiUser = identityService.newUser(userId);
			 identityService.saveUser(activitiUser);
	    }   
	  }
	  
	  
	  /**
	   * 使用系统用户对象属性设置到Activiti User对象中
	   * @param user		  系统用户对象
	   * @param activitiUser  Activiti User
	  
	  public void cloneAndSaveActivitiUser(User user, org.activiti.engine.identity.User activitiUser) {	    
		    activitiUser.setId(user.getId()); 
		    identityService.saveUser(activitiUser);
	 } */
	 
}
